package com.wsd.dao.impl;

import java.util.List;

import org.apache.commons.collections.functors.FalsePredicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wsd.bean.Users;
import com.wsd.dao.UsersDaoInterface;

/**
 * A data access object (DAO) providing persistence and search support for Users
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.wsd.bean.Users
 * @author MyEclipse Persistence Tools
 */

public class UsersDAO extends HibernateDaoSupport implements UsersDaoInterface{
	private static final Log log = LogFactory.getLog(UsersDAO.class);

	protected void initDao() {
		// do nothing
	}

	public void save(Users transientInstance) {
		log.debug("saving Users instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Users persistentInstance) {
		log.debug("deleting Users instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Users findById(java.lang.Integer id) {
		log.debug("getting Users instance with id: " + id);
		try {
			Users instance = (Users) getHibernateTemplate().get(
					"com.wsd.bean.Users", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Users> findByExample(Users user){
		log.debug("finding Users by example");
		try {
			return getHibernateTemplate().findByExample(user);
		} catch (RuntimeException re) {
			log.error("finding Users by example failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Users> findAll() {
		log.debug("finding all Users instances");
		try {
			String queryString = "from Users";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#findByUsername(java.lang.String)
	 */
	public List findByUsername(String username) {
		return getHibernateTemplate().find("from Users user where user.username = ?",username);
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#findByExample(com.wsd.bean.Users, int, int)
	 */
	public List<Users> findByExample(Users user, int start, int limit) {
		log.debug("finding Users by example");
		try {
			return getHibernateTemplate().findByExample(user, start, limit);
		} catch (RuntimeException re) {
			log.error("finding Users by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#findUsers(java.lang.Object[], java.lang.Object[], int, int)
	 */
	public List<Users> findUsers(String[] names, Object[] values, int start, int limit) {
		String sql = "from Users user" + buildSql(names,values,null) + " order by user.userid desc";
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		query.setFirstResult(start);
		query.setMaxResults(limit);
		
		return query.list();
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#findUsersCount(java.lang.String[], java.lang.Object[])
	 */
	public int findUsersCount(String[] names, Object[] values) {
		String sql = "select count(*) from Users user" + buildSql(names,values,null);
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		Long count = (Long) query.uniqueResult();
		return count.intValue();
	}

	/**
	 * @param names
	 * @param values
	 * @return
	 */
	private String buildSql(String[] names, Object[] values,String key) {
		StringBuilder sb = new StringBuilder("");
		boolean flag = false;
		int len = names.length;
		for(int i = 0; i < len; i++){
			if(!flag){
				sb.append(" where ");
				flag = true;
			}
			if( i > 0){
				sb.append(" and ");
			}
			sb.append(names[i] + " = " + values[i]);
		}
		if(key != null && flag){
			key = " and (userid like key or UName like key or username like key or company like key)".replace("key", "'%" + key + "%'");
			sb.append(key);
		}
		return sb.toString();
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#searchUsers(java.lang.String, java.lang.String[], java.lang.Object[], int, int)
	 */
	public List<Users> searchUsers(String key, String[] names, Object[] values, int start, int limit) {
		String sql = "from Users user" + buildSql(names,values,key); 
		System.out.println("search sql :::" + sql);
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		return query.list();
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#searchUsersCount(java.lang.String, java.lang.String[], java.lang.Object[])
	 */
	public int searchUsersCount(String key, String[] names, Object[] values) {
		String sql = "select count(*) from Users user" + buildSql(names,values,key);
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		Long count = (Long) query.uniqueResult();
		return count.intValue();
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#updateState(int, boolean)
	 */
	public void updateState(int userId, boolean state) {
		String sql = "update Users set state =:state where userId = :userId";
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		query.setBoolean("state", state);
		query.setInteger("userId", userId);
		query.executeUpdate();
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#updateLevel(int[], int)
	 */
	public void updateLevel(int userId, int userLevel) {
		String sql = "update Users set userLevel = :userLevel where userid = :userid";
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
		query.setInteger("userLevel", userLevel);
		query.setInteger("userid", userId);
		query.executeUpdate();
	
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.UsersDaoInterface#update(com.wsd.bean.Users)
	 */
	public void update(Users user) {
		getHibernateTemplate().update(user);
	}
}

	